package com.yl.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;

/**
 * json工具类
 */
public final class JsonUtil {

    /**
     * json转对象
     * @param json
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T parse(Object json, Class<T> t) {
        if(json == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
        try {
            return objectMapper.readValue(json.toString(), t);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对象转json
     * @param obj
     * @return
     */
    public static String parse(Object obj) {
        try {
            return  new ObjectMapper().registerModule(new JavaTimeModule()).writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return  null;
    }

}
